export type setIntervalCallBack = (resolve: (data?: any) => void, reject?: (err?: any) => void) => void
export type setIntervalPromise = (callback: setIntervalCallBack, interval: number, timeout: number) => Promise<any>

export const setIntervalPromise: setIntervalPromise = (callback, interval = 300, timeout = 6000) => {
    return new Promise((resolve, reject) => {
        let intervalId
        let timeoutId

        function clear() {
            intervalId && clearInterval(intervalId)
            timeoutId && clearTimeout(timeoutId)
        }

        try {
            timeoutId = setTimeout(() => {
                clear()
                reject(new Error('timeout'))
            }, timeout)

            intervalId = setInterval(() => {
                callback?.(
                    (data?: any) => {
                        clear()
                        resolve(data)
                    },
                    (err?: any) => {
                        clear()
                        reject(err)
                    })
            }, interval);
        } catch (e) {
            clear()
            reject(e)
        }
    })
}